package com.eastfair.certificate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.eastfair.certificate.dao.BadgeTemplateDetailMapper;
import com.eastfair.certificate.entity.BadgeTemplateDetail;
import com.eastfair.certificate.entity.CertificateUser;
import com.eastfair.certificate.service.BadgeTemplateDetailService;
import com.eastfair.boot.service.SuperServiceImpl;

import com.eastfair.core.context.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.Collection;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.eastfair.certificate.vo.*;
import com.eastfair.certificate.dto.*;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 业务实现类
 * 制证模板详情
 * </p>
 *
 * @author ligang
 * @date 2022-12-20
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class BadgeTemplateDetailServiceImpl extends SuperServiceImpl<BadgeTemplateDetailMapper, BadgeTemplateDetail> implements BadgeTemplateDetailService {

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    public R<Boolean> handlerSave(BadgeTemplateDetail model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTeamId(ContextUtil.getTeamId());
        model.setIsDeleted(BusinessConstant.NO);
        model.setIsEnabled(BusinessConstant.YES);
        //雪花ID
        return R.successDef();
    }

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<BadgeTemplateDetail> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<BadgeTemplateDetail> list(BadgeTemplateDetailDTO modelDTO, List<Long> ids) {
        return ((BadgeTemplateDetailService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'templateId', #args[0]?.templateId}," +
                            "{'field', #args[0]?.field}," +
                            "{'value', #args[0]?.value}," +
                            "{'teamId', #args[0]?.teamId}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<BadgeTemplateDetail> listOfCache(BadgeTemplateDetailDTO modelDTO, List<Long> ids) {
        //查询
        QueryWrapper<BadgeTemplateDetail> queryWrapper = new QueryWrapper<>();
        if (modelDTO != null) {
            queryWrapper.lambda().eq(modelDTO.getTemplateId() != null, BadgeTemplateDetail::getTemplateId, modelDTO.getTemplateId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getField()), BadgeTemplateDetail::getField, modelDTO.getField());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getValue()), BadgeTemplateDetail::getValue, modelDTO.getValue());
            queryWrapper.lambda().eq(modelDTO.getTeamId() != null, BadgeTemplateDetail::getTeamId, modelDTO.getTeamId());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(BadgeTemplateDetail::getId, ids);
        }
        queryWrapper.lambda().eq(BadgeTemplateDetail::getIsDeleted, BusinessConstant.DELETE_NO);
        List<BadgeTemplateDetail> modelList = list(queryWrapper);
        return modelList;
    }

    @Override
    public List<BadgeTemplateDetailVO> saveOfList(Long templateId, List<BadgeTemplateDetailDTO> badgeTemplateDetailDTOList) {
        List<BadgeTemplateDetailVO> result = new ArrayList<>();
        //清空之前数据
        BadgeTemplateDetailDTO badgeTemplateDetailDTO = new BadgeTemplateDetailDTO();
        badgeTemplateDetailDTO.setTemplateId(templateId);
        List<BadgeTemplateDetail> badgeTemplateDetailList = list(badgeTemplateDetailDTO, null);
        if (!CollectionUtils.isEmpty(badgeTemplateDetailList)) {
            if (CollectionUtil.isNotEmpty(badgeTemplateDetailDTOList)) {
                List<Long> ids = badgeTemplateDetailDTOList.stream().map(BadgeTemplateDetailDTO::getId).collect(Collectors.toList());
                for (BadgeTemplateDetail badgeTemplateDetail : badgeTemplateDetailList) {
                    if (!ids.contains(badgeTemplateDetail.getId())) {
                        badgeTemplateDetail.setIsDeleted(BusinessConstant.YES);
                        updateBatchById(badgeTemplateDetailList);
                    }
                }
            } else {
                for (BadgeTemplateDetail badgeTemplateDetail : badgeTemplateDetailList) {
                    badgeTemplateDetail.setIsDeleted(BusinessConstant.YES);
                    updateBatchById(badgeTemplateDetailList);
                }
            }

        }
        //重新添加数据
        for (BadgeTemplateDetailDTO badgeTemplateDetailDTO1 : badgeTemplateDetailDTOList) {
            BadgeTemplateDetail badgeTemplateDetail = new BadgeTemplateDetail();
            if (badgeTemplateDetailDTO1.getId() != null) {
                BeanUtils.copyProperties(badgeTemplateDetailDTO1, badgeTemplateDetail);
                badgeTemplateDetail.setTemplateId(templateId);
                updateById(badgeTemplateDetail);
            } else {
                BeanUtils.copyProperties(badgeTemplateDetailDTO1, badgeTemplateDetail);
                badgeTemplateDetail.setTemplateId(templateId);
                save(badgeTemplateDetail);
            }
            BadgeTemplateDetailVO badgeTemplateDetailVO = new BadgeTemplateDetailVO();
            BeanUtils.copyProperties(badgeTemplateDetail, badgeTemplateDetailVO);
            result.add(badgeTemplateDetailVO);
        }
        return result;
    }

    @Override
    public List<JSONObject> assembleDataOfJson(List<BadgeTemplateDetailVO> badgeTemplateDetailVOList) {
        List<JSONObject> badgeTemplateDetailJsonVOList = new ArrayList<>();
        for (BadgeTemplateDetailVO badgeTemplateDetailVO : badgeTemplateDetailVOList) {
            JSONObject jsonObject = JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(badgeTemplateDetailVO));
            JSONObject styleJson = JSONObject.parseObject(badgeTemplateDetailVO.getStyleTxt());
            for (String key : styleJson.keySet()) {
                if (jsonObject.keySet().contains(key)) {
                    jsonObject.put(key, jsonObject.get(key));
                } else {
                    jsonObject.put(key, styleJson.get(key));
                }

//                if (object == null) {
//                    jsonObject.put(key, styleJson.get(key));
//                }
            }
            jsonObject.remove("styleTxt");
            badgeTemplateDetailJsonVOList.add(jsonObject);
        }
        return badgeTemplateDetailJsonVOList;
    }

    @Override
    public List<BadgeTemplateDetailDTO> assembleData(List<JSONObject> badgeDetailJsonList) {
        List<BadgeTemplateDetailDTO> resultList = new ArrayList<>();
        for (JSONObject jsonObject : badgeDetailJsonList) {
            BadgeTemplateDetailDTO badgeTemplateDetailDTO = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.toString(), BadgeTemplateDetailDTO.class);
            badgeTemplateDetailDTO.setLeftSize(jsonObject.getDouble("leftSize"));
            badgeTemplateDetailDTO.setPrintRangeHeight(jsonObject.getString("printRangeHeight"));
            badgeTemplateDetailDTO.setPrintRangeWidth(jsonObject.getString("printRangeWidth"));
            badgeTemplateDetailDTO.setUnderline(jsonObject.getInteger("underline"));
            badgeTemplateDetailDTO.setTilt(jsonObject.getInteger("tilt"));
            badgeTemplateDetailDTO.setThickening(jsonObject.getInteger("thickening"));
            badgeTemplateDetailDTO.setTopSize(jsonObject.getDouble("topSize"));
            badgeTemplateDetailDTO.setValueType(jsonObject.getString("valueType"));
            badgeTemplateDetailDTO.setPrefixField(jsonObject.getString("prefixField"));
            jsonObject.remove("leftSize");
            jsonObject.remove("printRangeHeight");
            jsonObject.remove("printRangeWidth");
            jsonObject.remove("underline");
            jsonObject.remove("tilt");
            jsonObject.remove("thickening");
            jsonObject.remove("topSize");

            jsonObject.remove("valueType");
            jsonObject.remove("prefixField");

            badgeTemplateDetailDTO.setStyleTxt(jsonObject.toString());
            resultList.add(badgeTemplateDetailDTO);
        }
        return resultList;
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public BadgeTemplateDetailVO doToVo(BadgeTemplateDetail model) {
        BadgeTemplateDetailVO modelVo = new BadgeTemplateDetailVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<BadgeTemplateDetailVO> doToVos(List<BadgeTemplateDetail> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<BadgeTemplateDetailVO> result = new ArrayList<>();
        for (BadgeTemplateDetail model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }


}
